package com.bootx.officialAccount.job;

import com.bootx.NetImageHeaderType;
import com.bootx.entity.Article;
import com.bootx.officialAccount.entity.AccessToken;
import com.bootx.officialAccount.entity.Material;
import com.bootx.officialAccount.entity.NewsItem;
import com.bootx.officialAccount.entity.OfficialAccount;
import com.bootx.officialAccount.pojo.*;
import com.bootx.officialAccount.service.AccessTokenService;
import com.bootx.officialAccount.service.MaterialService;
import com.bootx.officialAccount.service.OfficialAccountService;
import com.bootx.officialAccount.util.DraftUtils;
import com.bootx.officialAccount.util.MaterialUtils;
import com.bootx.officialAccount.util.MediaUtils;
import com.bootx.service.ArticleService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author black
 */
@Component
public class ArticleJob {

    @Resource
    private ArticleService articleService;

    @Resource
    private OfficialAccountService officialAccountService;
    @Resource
    private AccessTokenService accessTokenService;
    @Resource
    private MaterialService materialService;

    @Resource
    private JdbcTemplate jdbcTemplate;

    @Scheduled(cron = "0 10 10 * * *")
    //@Scheduled(fixedRate = 1000*60*2)
    public void execute() {
        OfficialAccount officialAccount = officialAccountService.find(1L);
        AccessToken accessToken = accessTokenService.findByOfficialAccount(officialAccount);
        if(accessToken == null){
            return;
        }
        String accessTokenStr = accessToken.getAccessToken();
        StringBuffer querySql = new StringBuffer();
        querySql.append("select id from article where mediaId is null")
                .append(" and title not like '%比赛%'")
                .append(" and title not like '%大赛%'")
                .append(" and title not like '%征集%'")
                .append(" and title not like '%每日AI资讯%'")
                .append(" and content not like '%<video%'")
                .append(" order by id desc")
                .append(" limit 10")
        ;
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(querySql.toString());

        List<Article> list = new ArrayList<>();
        List<ArticlePojo> articles = new ArrayList<>();
        int newsCount = 0;
        if(maps.isEmpty()){
            return;
        }


        for (Map<String, Object> map : maps) {
            if (newsCount >= 8) {
                break;
            }
            Article article = articleService.find(Long.valueOf(String.valueOf(map.get("id"))));
            System.out.println(article.getId() + ":" + article.getUrl());
            ArticlePojo articlePojo = new ArticlePojo();
            articlePojo.setArticleType("news");
            articlePojo.setTitle(article.getTitle());
            articlePojo.setAuthor(article.getAuthor());
            if (StringUtils.isNoneBlank(article.getMemo())) {
                if (article.getMemo().length() > 100) {
                    articlePojo.setDigest(article.getMemo().substring(0, 54));
                } else {
                    articlePojo.setDigest(article.getMemo());
                }
            }
            articlePojo.setContent(parse(article.getContent(), accessTokenStr));
            articlePojo.setContentSourceUrl(article.getUrl());
            AddMaterialResponse uploadimg = MaterialUtils.addMaterial(accessTokenStr, article.getCover(), "image");
            articlePojo.setNeedOpenComment("1");
            if (uploadimg.getErrCode() == 0) {
                articlePojo.setThumbMediaId(uploadimg.getMediaId());
                articles.add(articlePojo);
            }
            list.add(article);
            newsCount = newsCount + 1;
        }
        DraftAddResponse draftAddResponse = DraftUtils.add(accessTokenStr, articles);
        String mediaId = draftAddResponse.getMediaId();
        // list
        list.forEach(article -> {
            jdbcTemplate.update("update article set mediaId=?,lastModifiedDate=NOW(),version=version+1 where id=?", mediaId, article.getId());
        });
    }

    private String parse(String content,String accessToken) {
        Document parse = Jsoup.parse(content);
        parse.getElementsByTag("img").forEach(element -> {
            String url = element.attr("src");
            int i = url.indexOf("?");
            if(i>=0){
                url = url.substring(0,i)+"?imageMogr2/format/png";
            } else if (NetImageHeaderType.getContentType(url).contains("image/webp")) {
                url = url+"?imageMogr2/format/png";
            }
            System.out.println(url);
            UploadImg uploadimg = MediaUtils.uploadimg(accessToken, url);
            element.attr("src", uploadimg.getUrl());
        });
        parse.getElementsByTag("video").forEach(element -> {
            String src = element.attr("src");
            String poster = element.attr("poster");
            if(StringUtils.isBlank(src)){
                src = element.getElementsByTag("source").first().attr("src");
                // 上传视频
                AddMaterialResponse addMaterialResponse = MaterialUtils.addMaterial(accessToken, src,"video");
                System.out.println(addMaterialResponse);
            }
            System.out.println("有视频");
        });
        parse.getElementsByTag("audio").forEach(element -> {
            System.out.println("有音频");
        });
        return parse.body().html();
    }

    //@Scheduled(fixedRate = 1000 * 60 * 60)
    public void run() {
        OfficialAccount officialAccount = officialAccountService.find(1L);
        AccessToken accessToken = accessTokenService.findByOfficialAccount(officialAccount);
        if(accessToken == null){
            return;
        }
        String accessTokenStr = accessToken.getAccessToken();
        int pageSize = 10;
        for (int i = 0; i < 100; i++) {
            BatchGetMaterial news = MaterialUtils.batchget_material(accessTokenStr, "image", i*pageSize, pageSize);
            System.out.println(news.getItem());
            List<BatchGetMaterial.ItemBean> item = news.getItem();
            item.forEach(itemBean -> {
                String mediaId = itemBean.getMediaId();
                Material material = new Material();
                material.setMediaId(mediaId);
                material.setUpdateTime(itemBean.getUpdateTime());
                material.setContent(new ArrayList<>());
                BatchGetMaterial.ItemBean.ContentBean content = itemBean.getContent();
                List<BatchGetMaterial.ItemBean.ContentBean.NewsItemBean> newsItems = content.getNewsItem();
                newsItems.forEach(newsItemBean -> {
                    NewsItem newsItem = new NewsItem();
                    BeanUtils.copyProperties(newsItemBean,newsItem);
                    System.out.println(newsItem);
                    material.getContent().add(newsItem);
                });
                materialService.create(material);
            });
        }



    }
}
